package com.ruoyi.web.controller.sample;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.samplemod.domain.entity.Sample;
import com.ruoyi.samplemod.service.ACBSampleService;
import com.ruoyi.samplemod.service.ACSampleService;
import com.ruoyi.samplemod.utils.ExcelListUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/acbsample")
public class ACBSampleController {

    @Autowired
    ACBSampleService sampleService;
    PageInfo<Sample> pageInfo;
    ExcelListUtils excelListUtils;
    String timeStar="",timeEnd="",sampleCode="";



    @GetMapping("/list")
    public PageInfo<Sample> sampleList(@RequestParam(defaultValue = "1") int pageNum,@RequestParam(defaultValue = "10") int pageSize){
        excelListUtils = sampleService.selectSample(pageSize, pageNum);
        pageInfo=excelListUtils.getPageInfo();
        return pageInfo;
    }

    @GetMapping("/endTime")
    public List<Sample> sampleList(){
        return sampleService.selectSampleAll();
    }

    @GetMapping("/list/ByNameByTime")
    public PageInfo<Sample> sampleListBy(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(defaultValue = "") String sampleCode,
            @RequestParam(defaultValue = "") String timeStar,
            @RequestParam(defaultValue = "") String timeEnd
            ){
        this.timeEnd=timeEnd;
        this.timeStar=timeStar;
        this.sampleCode=sampleCode;
        excelListUtils=sampleService.selectSampleByDataByName(timeStar,timeEnd,sampleCode,pageSize,pageNum);
        pageInfo=excelListUtils.getPageInfo();
        return pageInfo;
    }
    @PostMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
    // 1. Set response headers
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("样品数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 2. Get data
        List<Sample> dataList = sampleService.selectSampleByDataByNameExcel(timeStar,timeEnd,sampleCode);

        // 3. Create Excel writer with custom handler
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), Sample.class)
                .registerWriteHandler(new AbstractRowWriteHandler() {
                    @Override
                    public void afterRowDispose(WriteSheetHolder writeSheetHolder,
                                                WriteTableHolder writeTableHolder,
                                                Row row,
                                                Integer relativeRowIndex,
                                                Boolean isHead) {
                        // Add timestamp after last data row
                        if (!isHead && relativeRowIndex != null && relativeRowIndex == dataList.size() - 1) {
                            Sheet sheet = writeSheetHolder.getSheet();
                            int lastRowNum = sheet.getLastRowNum();

                            // 创建当前时间
                            Row timeRow = sheet.createRow(lastRowNum + 1);
                            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                            timeRow.createCell(0).setCellValue("导出时间:"+format);
                            // Merge cells if needed (columns 0-7)
                            sheet.addMergedRegion(new CellRangeAddress(
                                    lastRowNum + 1, // first row
                                    lastRowNum + 1, // last row
                                    0,              // first column
                                    7               // last column
                            ));
                        }
                    }
                })
                .build();

        // 4. Write data
        WriteSheet writeSheet = EasyExcel.writerSheet("样品列表").build();
        excelWriter.write(dataList, writeSheet);
        excelWriter.finish();
    }

    @PostMapping("/add")
    public String addSample(@Validated @RequestBody Sample sample){

        String username = SecurityUtils.getLoginUser().getUsername();
        sample.setUser(username);
        return sampleService.addSample(sample);
    }

    @DeleteMapping("/del/{Id}")
    public Long delSample(@PathVariable Long Id){
        return sampleService.delSample(Id);
    }



}
